from flask import Flask,render_template,request,make_response,session,jsonify,redirect,url_for,Response
from werkzeug.utils import secure_filename
import os

app = Flask(__name__)   # app是一个实例，传入的名字是当前模块
# app.secret_key="123123" # 官方建议要复杂一点，不容易破解
app.secret_key=os.urandom(16) # os.urandom(16) 系统自动生成16位的二进制加密密钥

# json 返回的格式有点问题（默认是ASCII码）
app.config["JSON_AS_ASCII"]=False

# 写一个最简单的get方法的服务
@app.route("/WoniuSales/")  # 结尾如果不写斜杠会自动补充 --- 确定资源的唯一性。
def WoniuSales():
    return render_template("WoniuSales.html") # 渲染模板,填写templates中的html名字就可以了

@app.route("/WoniuSales/user/login",methods=["POST"]) #methods=["POST"] 只支持POST方法
def user_login():

    # 如何获取此接口的上传数据？
    # request 对象： 固定的，不要改  --form flask import request
    username=request.form.get("username")
    password=request.form.get("password")
    verifycode=request.form.get("verifycode")

    print(f"上传的登录信息是：{username},{password},{verifycode}")
    #判断验证码是否正确
    if verifycode!="0000":
        return "vcode-error"
    elif username=="admin" and password=="admin123":
        # 登录成功需要Set-Cookie
        # 借助工具 make_response   --可以创建一个响应 (响应文本,状态码(默认200))
        response=make_response("login-pass",200) # 状态码可以不填
        response.set_cookie("username","admin",max_age=1000) #set_cookie("cookie的名字","cookie的值",max_age=1000（生存期秒）)
        response.set_cookie("password","admin123",max_age=1000)

        # 登录成功后需要设置 session
        # 借助工具session , 使用前需要添加一个secret key
        session["username"]="admin"   # 是一个字典
        session["password"]="admin123"
        return response # 把响应对象返回去
    else:
        # 判断账号密码对不对
        return "login-fail"

# 添加客户 需要cookie和session
@app.route("/WoniuSales/customer/add",methods=["POST"])
def customer_add():
    # 判断有没有cookies
    a=request.cookies
    c_username=request.cookies.get("username")    # 固定写法
    c_password=request.cookies.get("password")
    # 判断session
    s_username=session.get("username")
    print(f"cookies --> {c_username},{type(c_username)},{c_password}, session_username--->{s_username}")

    if c_username !=s_username  or c_username is  None or s_username is  None:  # 判断 cookie 和session 都有，并且值是一样。
        return "请登录",500
    elif request.form.get("customername") == "关羽1": # 判断是否重复添加
        return "already-added"
    else:
        return "add-successful"

@app.route("/WoniuSales/goods/upload",methods=["POST"])
def goods_upload():
    # 判断有没有cookies
    c_username = request.cookies.get("username")  # 固定写法
    c_password = request.cookies.get("password")
    # 判断session
    s_username = session.get("username")
    print(f"cookies --> {c_username},{type(c_username)},{c_password}, session_username--->{s_username}")

    if   c_username is None or s_username is None or c_username != s_username:  # 判断 cookie 和session 都有，并且值是一样。
        return "请登录", 500
    elif request.form.get("batchname") =="GB20200929":
        return "already-imported"
    else:
        # 把文件存下来

        # 1.获取文件
        file = request.files.get("batchfile")
        # 2. 获取文件名
        filename=file.filename
        print(filename)
        # 3. 保存
        # 这种方式是客户指定了什么名就是什么名
        # file.save( os.path.join(r"D:\tester_74\learn_flask_2",filename))  # 根据文件名保存上传的文件
        # 下面是官方推荐的文件名获取方案。
        file.save( os.path.join(r"D:\tester_74\learn_flask_2",secure_filename(file.filename)))  # 根据文件名保存上传的文件
        # 返回json格式的数据
        # 借助包jsonify  --转换为json数据响应
        return jsonify([{"createtime":"2020-09-29 09:29:40","quantity":10,"costunitprice":9.0,"goodsid":878,"goodsserial":"MT999999","totalprice":100.0,"inputsize":"0","goodsname":"夏季T恤","unitprice":10.0,"userid":1,"batchname":"GB2020092901","costtotalprice":90.0,"barcode":"0","goodstype":"0"},{"createtime":"2020-09-29 09:29:40","quantity":20,"costunitprice":19.0,"goodsid":879,"goodsserial":"MT555555","totalprice":400.0,"inputsize":"0","goodsname":"夏季帽子","unitprice":20.0,"userid":1,"batchname":"GB2020092901","costtotalprice":380.0,"barcode":"0","goodstype":"0"},{"createtime":"2020-09-29 09:29:40","quantity":30,"costunitprice":29.0,"goodsid":880,"goodsserial":"MT666666","totalprice":900.0,"inputsize":"0","goodsname":"夏季雨鞋","unitprice":30.0,"userid":1,"batchname":"GB2020092901","costtotalprice":870.0,"barcode":"0","goodstype":"0"},{"createtime":"2020-09-29 09:29:40","quantity":40,"costunitprice":39.0,"goodsid":881,"goodsserial":"MT777777","totalprice":1600.0,"inputsize":"0","goodsname":"夏季雨伞","unitprice":40.0,"userid":1,"batchname":"GB2020092901","costtotalprice":1560.0,"barcode":"0","goodstype":"0"},{"createtime":"2020-09-29 09:29:40","quantity":50,"costunitprice":49.0,"goodsid":882,"goodsserial":"MT888888","totalprice":2500.0,"inputsize":"0","goodsname":"夏季眼镜","unitprice":50.0,"userid":1,"batchname":"GB2020092901","costtotalprice":2450.0,"barcode":"0","goodstype":"0"},{"createtime":"2020-09-29 09:29:40","quantity":50,"costunitprice":49.0,"goodsid":883,"goodsserial":"MT444444","totalprice":2500.0,"inputsize":"0","goodsname":"夏季拖鞋","unitprice":50.0,"userid":1,"batchname":"GB2020092901","costtotalprice":2450.0,"barcode":"0","goodstype":"0"},{"createtime":"2020-09-29 09:29:40","quantity":50,"costunitprice":49.0,"goodsid":884,"goodsserial":"MT333333","totalprice":2500.0,"inputsize":"0","goodsname":"夏季短裤","unitprice":50.0,"userid":1,"batchname":"GB2020092901","costtotalprice":2450.0,"barcode":"0","goodstype":"0"}])


# 注销

@app.route("/WoniuSales/user/logout",methods=["GET"])
def user_logout():

    # 消掉cookie
    response=make_response("成功注销",302,{"Location":url_for("WoniuSales")}) # make_response("响应body",响应状态码,"字典方式表示头部")
    response.delete_cookie("username")
    response.delete_cookie("password")

    # 消掉session
    session.pop("username")
    session.pop("password")

    # 重定向到首页
    # return redirect("/WoniuSales/",code=302) # 方法一 ，必能重新定义响应body
    # return redirect(url_for("WoniuSales"),code=302) # 方法二： 官方推荐的 url_for("字符串格式的函数名")
    return response  # 方法三 ，自定义重定向，头部和body


if __name__ == '__main__':
    # port填写端口号（建议是 8000-9999）
    # debug=True ，开启调试模式， 代码修改后自动重启服务  ---- 方便
    app.run(port=9191,debug=True)





